<script setup>
import { componentList } from '../utils/config.js'
import draggable from 'vuedraggable'
import IssueItem from "./issueItem.vue"
import ContentContainer from "./contentContainer.vue"
import pannelIssueAttribute from "./pannelIssueAttribute.vue"
import pannelSurveyAttribute from "./pannelSurveyAttribute.vue"
import pannelStyle from './pannelStyle.vue'
import {createUniqueString} from "@/utils/index.js";
import {findSurveyIssueApi, getSurveyApi} from "@/api/feedback/survey.js";
import {listIssueByGroup} from "@/api/feedback/issue.js";
import { selectDictLabel} from "@/utils/ruoyi.js";
const props = defineProps({
  activeTab:Number
})
const route = useRoute();
const { proxy } = getCurrentInstance();
const {  fed_survey_group } = proxy.useDict('fed_survey_group')

const activeData = ref()
let tempActiveData

const issueList = ref([])

// 处理返回的数据
const generateData = (data)=>{
  return data.map(item=>({
    ...item,
    formId: item.field.split('-')[1],
    answer: item.type === 'multiple-check' ? item.answer.split(',') : item.answer
  }))
}

// 初始化数据
const initData =async (cb)=>{
  const { data } = await findSurveyIssueApi(route.query.surId)
  issueList.value = generateData(data)
  cb && typeof cb === 'function' && cb()
}
initData(()=>{
  activeData.value = issueList.value[0]
});



// 激活某项
function activeFormItem(element) {
  activeData.value = element
}
// 拷贝某项
function drawingItemCopy(item) {
  let clone = JSON.parse(JSON.stringify(item))
  clone.formId = createUniqueString()
  clone.field = `field-${clone.formId}`
  issueList.value.push(clone)
  activeData.value = clone
}
// 删除某项
function drawingItemDelete(index) {
  issueList.value.splice(index, 1)
  nextTick(() => {
    const len = issueList.value.length
    if (len) {
      activeData.value = issueList.value[len - 1];
    }
  })
}
function handleMoveUp(index) {
  if (index > 0) {
    // 交换位置
    const temp = issueList.value[index]
    issueList.value[index] = issueList.value[index - 1]
    issueList.value[index - 1] = temp
    // 激活移动后的项
    activeData.value = temp
  }
}

function handleMoveDown(index) {
  if (index < issueList.value.length - 1) {
    const temp = issueList.value[index]
    issueList.value[index] = issueList.value[index + 1]
    issueList.value[index + 1] = temp
    activeData.value = temp
  }
}

// 克隆组件逻辑
function cloneComponent(origin) {
  const clone = JSON.parse(JSON.stringify(origin))
  clone.formId = createUniqueString()
  clone.field = `field-${clone.formId}`
  clone.inStore = 'N'
  if(clone.issueId){
    delete clone.issueId
  }
  tempActiveData = clone
  return clone
}
// 从左侧拖拽结束逻辑
function onEnd(obj, a) {
  if (obj.from !== obj.to) {
    activeData.value = tempActiveData
  }
}

// ===============
// 获取题库数据
const issueStoreData = ref([])
const getQuestionBankByTag = async ()=>{
  const { data } = await  listIssueByGroup();
  issueStoreData.value = data;
}
getQuestionBankByTag();
// =================
const surveyData = ref({})
const getSurveyData = async ()=>{
  const { data } = await getSurveyApi(route.query.surId)
  surveyData.value = data
}
getSurveyData()


defineExpose({
  list: issueList,
  initData,
  surveyData
})
</script>

<template>
  <div class=" w-full flex flex-1 min-h-[0] border-t-[4px] border-t-solid border-[#eee]">
    <div class="w-[300px] h-full">
      <el-tabs type="border-card"  v-if="activeTab===0" class="flex-tabs">
        <el-tab-pane label="题型">
          <draggable class="grid grid-cols-2 gap-[8px]"  :sort="false" :clone="cloneComponent" @end="onEnd" :list="componentList" :group="{ name:'componentsGroup', pull:'clone', put:false }"  item-key="label">
              <template #item="{element,index}">
                <div   :key="index" class="btn-item">
                  {{element.typeName}}
                </div>
              </template>
          </draggable>
        </el-tab-pane>
        <el-tab-pane label="大纲">
          <draggable :list="issueList"
                     :animation="340"
                     item-key="label">
            <template #item="{ element, index }">
               <div class="mb-2 p-[10px] border rounded cursor-move bg-[#fafafa] hover:bg-gray-50">
                 第{{index+1}}题：{{ element.title}}
               </div>
            </template>
          </draggable>
        </el-tab-pane>
        <el-tab-pane label="题库">
          <el-collapse  :model-value="issueStoreData.map(item=>item.tag)">
            <el-collapse-item v-for="(item,index) in issueStoreData" :name="item.tag"  :title="selectDictLabel(fed_survey_group,item.tag)"  :key="index">
              <draggable class="grid grid-cols-3 gap-[8px]"  :sort="false" :clone="cloneComponent" @end="onEnd" :list="item.list" :group="{ name:'componentsGroup', pull:'clone', put:false }"  item-key="label">
                <template #item="{element,index}">
                  <div :key="index" class="btn-item hover:bg-[#eee]">{{element.keyword}}</div>
                </template>
              </draggable>

            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
      <el-tabs type="border-card"  v-if="activeTab===1" class="flex-tabs">
        <el-tab-pane label="样式设计">
          <pannelStyle :surveyData="surveyData" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <ContentContainer :list-data="issueList" :survey-data="surveyData" class="flex-1 min-w-[0] border-x-[4px] border-x-solid border-[#eee]">
      <draggable class="min-h-[500px]"
                 :list="issueList"
                 handle=".drag-handle"
                 :animation="340"
                 group="componentsGroup"
                 item-key="formId">
        <template #item="{ element, index }">
          <issue-item
              :key="element.formId"
              :showScore="surveyData.showScore === 'Y'"
              :showIndex="surveyData.showIndex === 'Y'"
              :showType="surveyData.showType === 'Y'"
              :editMode="activeTab===0"
              @activeItem="activeFormItem"
              @copyItem="drawingItemCopy"
              @deleteItem="drawingItemDelete"
              @moveUp="handleMoveUp"
              @moveDown="handleMoveDown"
              :activeData="activeData"
              :drawingList="issueList"
              :element="element"
              :index="index"
          />
        </template>
      </draggable>
    </ContentContainer>
    <div class="w-[300px] h-full">
      <pannelIssueAttribute   v-if="activeTab===0"  :drawingList="issueList" :active-data="activeData" />
      <pannelSurveyAttribute  v-if="activeTab===1" :surveyData="surveyData" />
    </div>
  </div>
</template>
<style scoped lang="scss">
.flex-tabs{
  display: flex;
  flex-direction: column;
  height:100%;
  :deep(.el-tabs__content){
    flex:1;
    min-height: 0;
    box-sizing: border-box;
    overflow-y: scroll;
  }
}
.btn-item{
  border: 1px solid rgba(0,0,0,.125);
  cursor: default;
  width: 100%;
  padding:8px 10px;
}
.content-scrollbar{
  height: calc(100vh - 50px - 40px - 42px);
}

</style>
